// scripts/data-validation.js
// 表单验证规则
const validationRules = {
    name: {
        required: true,
        minLength: 2,
        maxLength: 20
    },
    age: {
        required: true,
        min: 18,
        max: 100
    },
    email: {
        required: true,
        pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    },
    interest: {
        required: true,
        minLength: 5,
        maxLength: 50
    }
};

// 实时验证
document.getElementById('dataForm').addEventListener('input', (e) => {
    const field = e.target.name;
    const value = e.target.value;
    validateField(field, value);
});

function validateField(field, value) {
    const rules = validationRules[field];
    if(!rules) return;

    let isValid = true;
    const errorElement = document.getElementById(`${field}-error`);

    if(rules.required && !value.trim()) {
        showError(field, '必填项');
        isValid = false;
    }

    if(rules.minLength && value.length < rules.minLength) {
        showError(field, `至少${rules.minLength}个字符`);
        isValid = false;
    }

    if(rules.maxLength && value.length > rules.maxLength) {
        showError(field, `最多${rules.maxLength}个字符`);
        isValid = false;
    }

    if(rules.min && parseInt(value) < rules.min) {
        showError(field, `最小值${rules.min}`);
        isValid = false;
    }

    if(rules.max && parseInt(value) > rules.max) {
        showError(field, `最大值${rules.max}`);
        isValid = false;
    }

    if(rules.pattern && !rules.pattern.test(value)) {
        showError(field, '格式不正确');
        isValid = false;
    }

    return isValid;
}

function showError(field, message) {
    const errorElement = document.getElementById(`${field}-error`);
    errorElement.textContent = message;
    errorElement.style.display = 'block';
}

function clearError(field) {
    const errorElement = document.getElementById(`${field}-error`);
    errorElement.textContent = '';
    errorElement.style.display = 'none';
}
